extends Control



onready var name_input = $editaModal/VBoxContainer/name/LineEdit
onready var desc_input = $editaModal/VBoxContainer/desc/LineEdit

onready var modal = $editaModal
onready var search_input = $searchBox/LineEdit


var SpiritItem = preload("res://tool/page/poke/SpiritItem.tscn")
# 当前正在编辑的剧本数据，添加剧本数据为空
var edit_drama_data = null


func _ready():
	state_update()
	modal.visible = false


# 刷新页面状态
func state_update():
	update_list(DataSource.get_serie_spirit_list())

func update_list(list):
	var box = $table/ScrollContainer/VBoxContainer
	
	for child in box.get_children():
		child.queue_free()
		

	for data in list:
		var ui_item = SpiritItem.instance()
		ui_item.set_data(data)
		box.add_child(ui_item)
		ui_item.connect("attach_item", self, "_on_attach_item")


func state_update_modal():
	

	if edit_drama_data:
		$editaModal/modalTitle.text = "修改名称：%s" % [edit_drama_data["name"]]
		$editaModal/btns/ok.text = "确认"
		# 存在编辑数据
		name_input.text = edit_drama_data.get("newName", edit_drama_data.get("name", ""))
	else:
		$editaModal/modalTitle.text = "添加剧本"
		$editaModal/btns/ok.text = "创建剧本"


func _on_cancel_button_up():
	modal.visible = false



func _on_attach_item(poke_data):
	var ui = MainTool.getUILayer().add_ui("res://tool/page/poke/modal/SpriteAttachItemModal.tscn", 0, false)
	ui.set_data(poke_data)

func _on_ok_button_up():
	var data = edit_drama_data.duplicate(true)
	
	data["newName"] = name_input.text
	data["desc"] = desc_input.text
	
	DataSource.update_data(DataSource.poke, data)

	modal.visible = false
	state_update()


func _on_search_button_up():
	var text = search_input.text
	
	if text:
		var list = []
		for map in DataSource.get_serie_spirit_list():
			if map["name"].find(text) != -1:
				list.append(map)
				
		update_list(list)
	else:
		update_list(DataSource.get_serie_spirit_list())
